﻿<%@ WebHandler Language="C#" Class="structhandler" %>

using System;
using System.Web;

public class structhandler : AjaxHandlerBase {

    /// <summary>
    /// 获取组织部门人员
    /// 获取部门：idepartType参数为 0(默认)：门店；非0：所有当前用户所在公司的部门。日后可扩展该参数的外延
    /// 获取用户：iusertype参数为0(默认)：在职人员；-1:离职人员：1所有人员；
    /// </summary>
    /// <param name="context"></param>
    public override void RequestProcess(HttpContext context)
    {
        string strop = context.Request["op"];

        string strResponse = "";
        try
        {
            switch (strop.ToLower())
            {
                case "getcity"://获取城市
                    strResponse = GetCitys();
                    break;

                case "getcompany"://获取公司
                    Guid cityId = (string.IsNullOrEmpty(context.Request["fatherid"])) ? Guid.Empty : new Guid(context.Request["fatherid"]);
                    strResponse = GetCompanysByCity(cityId);
                    break;

                case "getbusinessdistrict"://根据公司ID获取商圈或者分类
                    Guid companyId = (string.IsNullOrEmpty(context.Request["fatherid"])) ? Guid.Empty : new Guid(context.Request["fatherid"]);
                    strResponse = GetDepartsByCompany(companyId, 4000);
                    break;

                case "getcompanydeparts"://根据公司ID获取部门或门店
                    Guid companyId2 = (string.IsNullOrEmpty(context.Request["fatherid"])) ? Guid.Empty : new Guid(context.Request["fatherid"]);
                    strResponse = GetDepartsByCompany(companyId2, 5000);
                    break;

                case "getdeparts"://根据商圈或分类ID获取部门
                    Guid fatherId = (string.IsNullOrEmpty(context.Request["fatherid"])) ? Guid.Empty : new Guid(context.Request["fatherid"]);
                    strResponse = GetDepartsByFather(fatherId);
                    break;
                case "getourdeparts":
                    strResponse = GetOurCompanyDeparts();
                    break;

                case "getemployee"://根据部门获取人员
                    Guid departId = (string.IsNullOrEmpty(context.Request["fatherid"])) ? Guid.Empty : new Guid(context.Request["fatherid"]);
                    int iusertype = (string.IsNullOrEmpty(context.Request["usertype"])) ? 1 : int.Parse(context.Request["usertype"]);

                    strResponse = GetDepartmentUsers(departId, iusertype);
                    break;
                case "getcontroldeparts"://得到登录人的可控制部门
                    strResponse = GetControlDeparts();
                    break;
                case "getallotdeparts"://获取分配时可以选择的部门，参数 fatherid;
                    Guid companyIdv = (string.IsNullOrEmpty(context.Request["fatherid"])) ? Guid.Empty : new Guid(context.Request["fatherid"]);
                    strResponse = getallotdeparts(companyIdv);
                    break;
                case "getallotusers"://获取房源分配时可以选择的人员，参数 fatherid;
                    Guid departId1 = (string.IsNullOrEmpty(context.Request["fatherid"])) ? Guid.Empty : new Guid(context.Request["fatherid"]);
                    strResponse = getallotusers(departId1);
                    break;
                case "getallotusers_customer"://获取客需分配时可以选择的人员，参数 fatherid;
                    Guid departId2 = (string.IsNullOrEmpty(context.Request["fatherid"])) ? Guid.Empty : new Guid(context.Request["fatherid"]);
                    strResponse = getallotusers_customer(departId2);
                    break;    
                default:
                    break;
            }
        }
        catch (Exception ex)
        {
            strResponse = string.Format("{{success:'0',msg:'意外错误：{0}',data:{{items:[]}}}}", ex.Message);
        }
        context.Response.AddHeader("pragma", "no-cache");
        context.Response.AddHeader("cache-control", "");
        context.Response.CacheControl = "no-cache";
        context.Response.Write(strResponse);
    }

    private string getallotusers_customer(Guid departId)
    {
        if (departId == Guid.Empty)
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", "未选择部门");

        System.Collections.Generic.List<Chenxin.Lib.Passport.Entity.Hr_UserInfo> userlist = null;
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        if (CurrentUserInfo.ContainsPermit(Chenxin.Lib.Utility.Constants.Permit_Allot_Depart_AllUser))
        {
            sb.AppendFormat("(exists(select OprPersonId From Chenxin_House.dbo.Customer_DemandInfo where OprPersonId = Hr_UserInfo.UserId AND OprDepartId='{0}'))", departId);
        }
        else if (CurrentUserInfo.ContainsPermit(Chenxin.Lib.Utility.Constants.Permit_Allot_Depart_OnlyLeaveUser))
        {
            sb.Append("(((IsVirtual = 0) AND (Status = -1)) AND  ");
            sb.AppendFormat("(exists(select OprPersonId From Chenxin_House.dbo.Customer_DemandInfo where OprPersonId = Hr_UserInfo.UserId AND OprDepartId='{0}')))", departId);
        }
        else
        {
            return retExecResult(Chenxin.Lib.Utility.Constants.ExecResult.Error, "请检查分配权限", "");
        }

        userlist = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetListArray(sb.ToString(), "UserName");
        System.Text.StringBuilder str = new System.Text.StringBuilder();

        foreach (Chenxin.Lib.Passport.Entity.Hr_UserInfo item in userlist)
        {
            str.Append("{ txt: '" + item.UserName.Trim() + "(" + item.UserCode + ")" + "', val: '" + item.UserId.ToString() + "' },");
        }
        if (str.Length > 0) str.Remove(str.Length - 1, 1);
        return string.Format("{{success:'1',msg:'成功',data:{{items:[{0}]}}}}", str.ToString());
    }
    

    private string getallotusers(Guid departId)
    {
        if (departId == Guid.Empty)
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", "未选择部门");

        System.Collections.Generic.List<Chenxin.Lib.Passport.Entity.Hr_UserInfo> userlist = null;
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        
        if (CurrentUserInfo.ContainsPermit(Chenxin.Lib.Utility.Constants.Permit_Allot_Depart_AllUser))
        {
            sb.AppendFormat("(exists(select OprPersonId From Chenxin_House.dbo.House_BaseInfo where OprPersonId = Hr_UserInfo.UserId AND OprDepartId='{0}'))", departId);
        }
        else if (CurrentUserInfo.ContainsPermit(Chenxin.Lib.Utility.Constants.Permit_Allot_Depart_OnlyLeaveUser))
        {
            //sb.AppendFormat("(((IsVirtual = 0) AND (DepartId = '{0}') AND (Status = -1)) AND  ", departId);
            sb.Append("(((IsVirtual = 0) AND (Status = -1)) AND  ");
            sb.AppendFormat("(exists(select OprPersonId From Chenxin_House.dbo.House_BaseInfo where OprPersonId = Hr_UserInfo.UserId AND OprDepartId='{0}')))", departId);
        }
        else
        {
            return retExecResult(Chenxin.Lib.Utility.Constants.ExecResult.Error, "请检查分配权限", "");
        }

        userlist = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetListArray(sb.ToString(), "UserName");
        System.Text.StringBuilder str = new System.Text.StringBuilder();
        
        foreach (Chenxin.Lib.Passport.Entity.Hr_UserInfo item in userlist)
        {
            str.Append("{ txt: '" + item.UserName.Trim() + "(" + item.UserCode + ")" + "', val: '" + item.UserId.ToString() + "' },");
        }
        if (str.Length > 0) str.Remove(str.Length - 1, 1);
        return string.Format("{{success:'1',msg:'成功',data:{{items:[{0}]}}}}", str.ToString());
    }
    
    private string getallotdeparts(Guid companyId)
    {
        System.Collections.Generic.List<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo> listDeparts = null;
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        try
        {
            if (CurrentUserInfo.ContainsPermit(Chenxin.Lib.Utility.Constants.Permit_Allot_All))
            {
                if (companyId == Guid.Empty)
                    sb.Append(" (IsOpen = 1) AND (DepartProperty = 500 Or DepartProperty = 600)");
                else
                    sb.AppendFormat(" (IsOpen = 1) AND (DepartProperty = 500 Or DepartProperty = 600) AND (CompanyId = '{0}')", companyId);
            }
            else if (CurrentUserInfo.ContainsPermit(Chenxin.Lib.Utility.Constants.Permit_Allot_Company))
            {
                if (companyId == Guid.Empty)
                    sb.AppendFormat(" (IsOpen = 1) AND (DepartProperty = 500 Or DepartProperty = 600) AND (CompanyId = '{0}')", CurrentUserInfo.CompanyId);
                else
                    sb.AppendFormat(" (IsOpen = 1) AND (DepartProperty = 500 Or DepartProperty = 600) AND (CompanyId = '{0}')", companyId);
            }
            else
            {
                if (companyId == Guid.Empty)
                {
                    sb.AppendFormat(" CompanyId = '{0}' AND exists(select 1 from Struct_UserDepartRelation M ", CurrentUserInfo.CompanyId);
                    sb.AppendFormat("Where Hr_DepartmentInfo.DepartID = M.DepartId AND M.UserId='{0}' and M.IsControl=1)", CurrentUserInfo.UserId);
                }
                else
                {
                    sb.AppendFormat(" CompanyId = '{0}' AND exists(select 1 from Struct_UserDepartRelation M ", companyId);
                    sb.AppendFormat("Where Hr_DepartmentInfo.DepartID = M.DepartId AND M.UserId='{0}' and M.IsControl=1)", CurrentUserInfo.UserId);
                }
            }

            listDeparts = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetListArray(sb.ToString(), " DepartName ");
            

            //生成JSON字符串
            System.Text.StringBuilder str = new System.Text.StringBuilder();
            foreach (Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item in listDeparts)
            {
                str.Append("{ txt: '" + item.DepartName + "', val: '" + item.DepartId + "' },");
            }
            if (str.Length > 0)
            {
                str.Remove(str.Length - 1, 1);
            }
            return string.Format("{{success:'1',msg:'成功',data:{{items:[{0}]}}}}", str.ToString());
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }
    
    /// <summary>
    /// 根据父级别ID获取所有子级部门或门店
    /// </summary>
    /// <param name="fatherId"></param>
    /// <returns></returns>
    private string GetDepartsByFather(Guid fatherId)
    {
        try
        {
            System.Collections.Generic.List<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo> departlist = null;//new System.Collections.Generic.List<Chenxin.Lib.House.Entity.DataDictionary>();

            //首先从缓存中获取数据
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_STRUCT_TREE, fatherId);
            departlist = cs.GetList<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCacheKey);

            if (!cs.Hit)//若缓存未命中，则从数据库中获取并存入缓存，时间为1天
            {
                Chenxin.Lib.Cache.CacheService cs2 = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                string strCachKey2 = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_DEPARTMENT, fatherId);

                Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo father = null;
                father = cs2.GetObject<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCachKey2);
                if (!cs2.Hit)
                {
                    father = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetModel(fatherId);
                    if (father!=null) cs2.Set(strCachKey2, father, DateTime.Now.AddDays(1));
                }

                if (father == null) return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", "父节点不存在");
                
                System.Text.StringBuilder sb = new System.Text.StringBuilder();

                sb.AppendFormat(" (IsOpen = 1) AND (DepartProperty = 500 Or DepartProperty = 600) AND (DepartSrc like '{0}%')", father.DepartSrc);

                string strOrder = " DepartName";
                departlist = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetListArray(sb.ToString(), strOrder);

                if (departlist != null && departlist.Count > 0) cs.Set(strCacheKey, departlist, DateTime.Today.AddDays(1));
            }


            //生成JSON字符串
            System.Text.StringBuilder str = new System.Text.StringBuilder();
            foreach (Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item in departlist)
            {
                str.Append("{ txt: '" + item.DepartName.Trim() + "', val: '" + item.DepartId.ToString() + "' },");
            }
            if (str.Length > 0) str.Remove(str.Length - 1, 1);
            return string.Format("{{success:'1',msg:'成功',data:{{items:[{0}]}}}}", str.ToString());
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }
    
    /// <summary>
    /// iusertype参数为1(默认)：在职人员；-1:离职人员：0所有人员；
    /// </summary>
    /// <param name="departId"></param>
    /// <param name="itype"></param>
    /// <returns></returns>
    private string GetDepartmentUsers(Guid departId, int itype)
    {
        try
        {
            System.Collections.Generic.List<Chenxin.Lib.Passport.Entity.Hr_UserInfo> userlist = null;//new System.Collections.Generic.List<Chenxin.Lib.House.Entity.DataDictionary>();

            //首先从缓存中获取数据
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.HR);
            string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.HR_DEPARTMENT_USERS, departId.ToString() + "." + itype.ToString());
            userlist = cs.GetList<Chenxin.Lib.Passport.Entity.Hr_UserInfo>(strCacheKey);

            if (!cs.Hit)//若缓存未命中，则从数据库中获取并存入缓存，时间为1天
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.AppendFormat("(departId = '{0}' AND Validate = 1 AND IsVirtual = 0)", departId);
                if (itype != 0) sb.AppendFormat(" AND (Status = {0})", itype);

                string strOrder = " UserName";

                userlist = Chenxin.Lib.Passport.DAL.Hr_UserInfo.GetListArray(sb.ToString(), strOrder);

                cs.Set(strCacheKey, userlist, DateTime.Today.AddDays(1));
            }


            //生成JSON字符串
            System.Text.StringBuilder str = new System.Text.StringBuilder();
            foreach (Chenxin.Lib.Passport.Entity.Hr_UserInfo item in userlist)
            {
                str.Append("{ txt: '" + item.UserName.Trim() + "(" + item.SerialCode + ")" + "', val: '" + item.UserId.ToString() + "' },");
            }
            if (str.Length > 0) str.Remove(str.Length - 1, 1);
            return string.Format("{{success:'1',msg:'成功',data:{{items:[{0}]}}}}", str.ToString());
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }
    
    /// <summary>
    /// 获取我公司所有门店
    /// </summary>
    /// <returns></returns>
    private string GetOurCompanyDeparts()
    {
        Guid companyId = CurrentUserInfo.CompanyId;
        return GetDepartsByCompany(companyId, 5000);
    }

    /// <summary>
    /// 根据公司ID获取公司部门
    /// </summary>
    /// <param name="companyId"></param>
    /// <param name="type">4000:商圈/分类；5000:门店/其他部门;0:所有部门</param>
    /// <returns></returns>
    private string GetDepartsByCompany(Guid companyId, int type)
    {
        try
        {
            System.Collections.Generic.List<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo> departlist = null;//new System.Collections.Generic.List<Chenxin.Lib.House.Entity.DataDictionary>();

            //首先从缓存中获取数据
            Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
            string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_STRUCT_TREE, companyId.ToString() + "." + type.ToString());
            departlist = cs.GetList<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCacheKey);

            if (!cs.Hit)//若缓存未命中，则从数据库中获取并存入缓存，时间为1天
            {
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                if (type == 4000)
                {
                    sb.AppendFormat("(DepartProperty = 300 OR DepartProperty = 400) AND (companyId = '{0}') And (IsOpen = 1) ", companyId);
                }
                else if (type == 5000)
                {
                    sb.AppendFormat("(DepartProperty = 500 OR DepartProperty = 600) AND (companyId = '{0}') AND (IsOpen = 1) ", companyId);
                }
                else if (type == 0)
                {
                    sb.AppendFormat("(companyId = '{0}')", companyId);
                }
                else
                {
                    sb.AppendFormat("(DepartProperty = {1}) AND (companyId = '{0}')", companyId, type);
                }

                string strOrder = " DepartName";
                departlist = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetListArray(sb.ToString(), strOrder);

                cs.Set(strCacheKey, departlist, DateTime.Today.AddDays(1));
            }


            //生成JSON字符串
            System.Text.StringBuilder str = new System.Text.StringBuilder();
            foreach (Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item in departlist)
            {
                str.Append("{ txt: '" + item.DepartName.Trim() + "', val: '" + item.DepartId.ToString() + "' },");
            }
            if (str.Length > 0) str.Remove(str.Length - 1, 1);
            return string.Format("{{success:'1',msg:'成功',data:{{items:[{0}]}}}}", str.ToString());
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }

    /// <summary>
    /// 获取登录人员可控制的部门列表
    /// </summary>
    /// <returns></returns>
    private string GetControlDeparts()
    {
        try
        {
           System.Data.DataSet ds = CurrentUserInfo.GetUserControledDeparts();

            //生成JSON字符串
            System.Text.StringBuilder str = new System.Text.StringBuilder();
            foreach (System.Data.DataRow dr in ds.Tables[0].Rows)
            {
                str.Append("{ txt: '" + dr["DepartName"] + "', val: '" + dr["DepartId"] + "' },");
            }
            if (str.Length > 0)
            {
                str.Remove(str.Length - 1, 1);
            }
            return string.Format("{{success:'1',msg:'成功',data:{{items:[{0}]}}}}", str.ToString());
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }
    
    /// <summary>
    /// 获取指定城市的公司列表
    /// </summary>
    /// <param name="cityId"></param>
    /// <returns></returns>
    private string GetCompanysByCity(Guid cityId)
    {
        try
        {
            System.Collections.Generic.List<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo> companylist = null;//new System.Collections.Generic.List<Chenxin.Lib.House.Entity.DataDictionary>();

            string permitCode = Chenxin.Lib.Utility.Constants.Permit_SelectAllCompany;
            System.Text.StringBuilder str = new System.Text.StringBuilder();
            
            if (CurrentUserInfo.ContainsPermit(permitCode))
            {
                //首先从缓存中获取数据
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_STRUCT_TREE, cityId);
                companylist = cs.GetList<Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo>(strCacheKey);

                if (!cs.Hit)//若缓存未命中，则从数据库中获取并存入缓存，时间为1天
                {
                    System.Text.StringBuilder sb = new System.Text.StringBuilder();
                    sb.AppendFormat("(DepartProperty = 200) AND (CityId = '{0}')", cityId);

                    string strOrder = " DepartName";
                    companylist = Chenxin.Lib.Hr.DAL.Hr_DepartmentInfo.GetListArray(sb.ToString(), strOrder);

                    cs.Set(strCacheKey, companylist, DateTime.Today.AddDays(1));
                }


                //生成JSON字符串
                foreach (Chenxin.Lib.Hr.Entity.Hr_DepartmentInfo item in companylist)
                {
                    str.Append("{ txt: '" + item.DepartName.Trim() + "', val: '" + item.DepartId.ToString() + "' },");
                }
                if (str.Length > 0) str.Remove(str.Length - 1, 1);
            }
            else
            {
                str.Append("{ txt: '" + CurrentUserInfo.CompanyName.Trim() + "', val: '" + CurrentUserInfo.CompanyId.ToString() + "' }");
            }

            return string.Format("{{success:'1',msg:'成功',data:{{items:[{0}]}}}}", str.ToString());
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }
    /// <summary>
    /// 获取所有城市列表
    /// </summary>
    /// <returns></returns>
    private string GetCitys()
    {
        try
        {
            System.Collections.Generic.List<Chenxin.Lib.Hr.Entity.Struct_CityBaseInfo> citylist = null;//new System.Collections.Generic.List<Chenxin.Lib.House.Entity.DataDictionary>();

            string permitCode = Chenxin.Lib.Utility.Constants.Permit_SelectAllCity;
            System.Text.StringBuilder str = new System.Text.StringBuilder();

            if (CurrentUserInfo.ContainsPermit(permitCode))
            {
                //首先从缓存中获取数据
                Chenxin.Lib.Cache.CacheService cs = new Chenxin.Lib.Cache.CacheService(Chenxin.Lib.Cache.CacheConn.xCacheConn.GLOBAL);
                string strCacheKey = string.Format(Chenxin.Lib.Cache.CacheDataType.GLOBAL_CITYS);
                citylist = cs.GetList<Chenxin.Lib.Hr.Entity.Struct_CityBaseInfo>(strCacheKey);

                if (!cs.Hit)//若缓存未命中，则从数据库中获取并存入缓存，时间为1天
                {
                    citylist = Chenxin.Lib.Hr.DAL.Struct_CityBaseInfo.GetListArray("");

                    cs.Set(strCacheKey, citylist, DateTime.Today.AddDays(1));
                }

                //生成JSON字符串
                foreach (Chenxin.Lib.Hr.Entity.Struct_CityBaseInfo item in citylist)
                {
                    str.Append("{ txt: '" + item.CityName.Trim() + "', val: '" + item.CityId.ToString() + "' },");
                }
                if (str.Length > 0) str.Remove(str.Length - 1, 1);
            }
            else
            {
                str.Append("{ txt: '" + CurrentUserInfo.CityName.Trim() + "', val: '" + CurrentUserInfo.CityId.ToString() + "' }");
            }
            
            return string.Format("{{success:'1',msg:'成功',data:{{items:[{0}]}}}}", str.ToString());
        }
        catch (Exception ex)
        {
            return string.Format("{{success:'0',msg:'意外错误：{0}',data:''}}", ex.Message);
        }
    }
}